﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using TrinityAPI.Base.Tools;

namespace TrinityAPI.Base.Models
{
    public class Function
    {
        private string _name;
        private JToken[] _args;

        public string Name
        {
            get { return _name; }
        }

        public JToken[] Args
        {
            get { return _args; }
        }

        public Function(string name, JToken[] args)
        {
            this._name = name;
            this._args = args ?? new JToken[0];
        }

        public Function(string name, string argument, JObject dataset)
        {
            JToken[] args = null;
            if (!string.IsNullOrWhiteSpace(argument))
            {
                if (argument.IndexOf(",") == -1)
                {
                    string arg = argument.Trim(' ');
                    args = new JToken[1];
                    args[0] = arg.StartsWith("@") ? Utils.GetParameter(arg.TrimStart('@'), dataset).Evaluate() : arg;
                }
                else
                {
                    bool isComma = false;
                    if (argument.IndexOf("','") > -1)
                    {
                        isComma = true;
                        argument = argument.Replace("','", ")"); //如果存在逗号，将逗号替换成“右括号”。因为参数不可能存在“右括号”
                    }
                    string[] arguments = argument.Split(',');
                    args = new JToken[arguments.Length];
                    for (int i = 0; i < arguments.Length; i++)
                    {
                        string arg = arguments[i].Trim(' ');
                        if (isComma)
                            arg = arg.Replace(")", ","); //将“右括号”替换回逗号
                        args[i] = arg.StartsWith("@") ? Utils.GetParameter(arg.TrimStart('@'), dataset).Evaluate() : arg;
                    }
                }
            }
            this._name = name;
            this._args = args ?? new JToken[0];
        }
    }
}
